<?php
namespace  Admin\Controller;
use Think\Controller;
use Think\Page;
use Org\Net\Http;
use Think\Image;
class UserController extends AuthController{
	public function index(){
		$user=D('User');
		$list = $user->order(array('ctime'=>'asc'))->select();
		$area=D('Area');
		$areas = $area->order(array('id'=>'asc'))->select();
		$this->assign('areas',$areas);
		$this->assign('list',$list);
		$this->display();
	}
	
	public function addUser(){
		if(IS_POST){
			$user = D('User');
			$data = $user->create($_POST);
			
			if($data){
				$file = $_FILES['image'];
				if($file['size']>0){
					$uploadpath = "Public/Upload/User/";//上传路径
					if (!file_exists($uploadpath)){
						mkdir($uploadpath, 0777);
					}
					$pinfo = pathinfo($file['name']);
					$ftype = $pinfo['extension'];//文件类型
					$name = basename($file['name'],".{$ftype}");
						
					$fileName = md5($name.time()).".".$ftype;//识别图
					$image = new Image();
					$image->open($file['tmp_name']);
					$image->save($uploadpath.$fileName);
					$data['image'] = 'http://'.$_SERVER['HTTP_HOST'].'/'.__ROOT__.'/'.$uploadpath.$fileName;
				}
				$result = $user->add($data);
				if($result){
					$address['uid'] = $result;
					$address['name'] = $data['name'];
					$address['phone_number'] = $data['phone_number'];
					$address['area'] = $data['area'];
					$address['address'] = $data['address'];
					$address_id = M("Address")->add($address);
					if($address_id){
						$user->where(array('id'=>$result))->save(array("address_id"=>$address_id));
						$this->success("添加成功","index");
					}else{
						$this->error("添加地址失败");
					}
				}else{
					$this->error("添加失败");
				}
			}else{
				$this->error($user->getError());
			}
		}
	}
	public function update(){
		if(IS_POST){
			$file = $_FILES['update_image'];
			$data = $_POST;
			if($file['size']>0){
				$uploadpath = "Public/Upload/User/";//上传路径
				if (!file_exists($uploadpath)){
					mkdir($uploadpath, 0777);
				}
				$pinfo = pathinfo($file['name']);
				$ftype = $pinfo['extension'];//文件类型
				$name = basename($file['name'],".{$ftype}");
					
				$fileName = md5($name.time()).".".$ftype;//识别图
				$image = new Image();
				$image->open($file['tmp_name']);
				$image->save($uploadpath.$fileName);
				$data['image'] = 'http://'.$_SERVER['HTTP_HOST'].'/'.__ROOT__.'/'.$uploadpath.$fileName;
			}
			if($data['password'] == ""){
				unset($data['password']);
			}else{
				$data['password'] = md5($data['password']);
			}
			$where['id'] = $_POST['id'];
			$user = D('User');
			$result = $user->where($where)->save($data);
			if($result){
				$this->success("修改成功","index");
			}else{
				$this->error("修改失败");	
			}
		}
	}
}
?>